<template>
    <div class="app-container">
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px" style="padding-right: 5px;">
        <el-row>
          <el-col :span="8">
            <el-form-item label="年份" prop="yearSign" style="width: 100%;">
              <el-select v-model="queryParams.yearSign" placeholder="请选择年份" @change="handleQuery">
                  <el-option
                    v-for="dict in yearOptions"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <!--<el-col :span="8" style="padding-left: 12px; padding-right: 12px;">
            <el-form-item label="月份" prop="month" style="width: 100%;">
              <el-select v-model="queryParams.month" placeholder="请选择月份" clearable>
                  <el-option
                    v-for="dict in monthOptions"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"/>
              </el-select>
            </el-form-item>
          </el-col>-->
          <el-col :span="8" style="padding-left: 12px;">
            <el-form-item label="申报对象" prop="deptName" style="width: 100%;">
              <el-input
                v-model="queryParams.deptName"
                placeholder="请输入申报对象"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="组织" prop="deptId" style="width: 100%;">
              <el-tree-select
                v-model="queryParams.deptId"
                :data="deptOptions"
                :props="{ value: 'deptId', label: 'deptName', children: 'children' }"
                value-key="deptId"
                placeholder="请选择组织"
                check-strictly
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
  
      <el-row :gutter="10" class="mb8" style="margin: 15px 0px;">
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="Download"
            @click="handleExport"
            v-hasPermi="['partybuilding:WorkScore:export']"
          >导出</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
              icon="UserFilled"
              @click="handleAudit"
              v-hasPermi="['partybuilding:WorkScore:approveOrg']"
          >积分审批</el-button>
        </el-col>
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" @handleQuery="handleQuery" @resetQuery="resetQuery"></right-toolbar>
      </el-row>
  
      <el-table v-loading="loading" :data="WorkScoreList" @selection-change="handleSelectionChange">
        <el-table-column type="index" label="排名" align="center" width="90"></el-table-column>
        <el-table-column label="组织名称" align="left" prop="deptName" />
        <el-table-column label="积分" align="left" prop="scoreSum" />
        <el-table-column label="操作" align="left" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="danger" @click="handleApply(scope.row)" v-hasPermi="['partybuilding:WorkScore:applyForAddingOrg']">积分申报</el-button>
            <el-divider direction="vertical" />
            <el-button link type="danger" @click="handleDetail(scope.row)" v-hasPermi="['partybuilding:WorkScore:queryOrg']">积分明细</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
  
      <!-- 积分申报 -->
      <apply-score ref="applyScoreRef"/>

      <!-- 积分明细 -->
      <score-detail ref="detailScoreRef"/>

      <!-- 积分审批 -->
      <audit-score ref="auditScoreRef"/>
    </div>
  </template>
  
  <script setup name="WorkScore">
  import { listOrg } from "@/api/partybuilding/Org";
  import { listWorkScore, getWorkScore, delWorkScore, addWorkScore, updateWorkScore } from "@/api/partybuilding/WorkScore";
  import ApplyScore from './component/ApplyScore.vue'
  import ScoreDetail from './component/ScoreDetail.vue'
  import AuditScore from './component/AuditScore.vue'
  
  const { proxy } = getCurrentInstance();
  
  const WorkScoreList = ref([]);
  const open = ref(false);
  const openScore = ref(false);
  const openAudit = ref(false);
  const loading = ref(true);
  const showSearch = ref(true);
  const ids = ref([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);
  const title = ref("");
  const deptOptions = ref(undefined);
  const yearOptions = ref([]);
  const monthOptions = ref([]);
  const applyScoreRef = ref(null);
  const detailScoreRef = ref(null);
  const auditScoreRef = ref(null);
    
  const data = reactive({
    form: {},
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      userId: null,
      userName: null,
      deptId: null,
      orgName: null,
      type: 1,
      typeName: null,
      typeId: null,
      title: null,
      titleId: null,
      cycle: null,
      scoreOrigin: null,
      addScore: null,
      approvalStatus: null,
      approvalRemark: null,
      approvalRecord: null
    },
    queryScoreParams: {
      pageNum: 1,
      pageSize: 10,
      year: null,
      userName: null,
      startTime: null,
      endTime: null
    },
    rules: {
      type: [
        { required: true, message: "0党员积分，1组织积分不能为空", trigger: "change" }
      ],
      titleId: [
        { required: true, message: "题目id不能为空", trigger: "blur" }
      ],
      addScore: [
        { required: true, message: "申请积分不能为空", trigger: "blur" }
      ],
    }
  });
  
  const { queryParams, form, rules } = toRefs(data);
  
  function handleApply(row) {
    applyScoreRef.value.refresh(row.deptId, queryParams.value.yearSign, 1, row.scoreSum, row.deptName, null, null);
  }
  
  function handleDetail(row) {
    detailScoreRef.value.refresh(row.deptId, queryParams.value.yearSign, 1, row.scoreSum);
  }

  function handleAudit() {
    auditScoreRef.value.refresh(null, queryParams.value.yearSign, 1);
  }

  /** 查询党员积分列表 */
  function getList() {
    loading.value = true;
    if (queryParams.value.yearSign == null || queryParams.value.yearSign == "") {
      queryParams.value.yearSign = new Date().getFullYear();
    }
    listWorkScore(queryParams.value).then(response => {      
      WorkScoreList.value = response.rows;
      total.value = response.total;
      loading.value = false;
    });
  }
  
  // 取消按钮
  function cancel() {
    open.value = false;
    reset();
  }
  
  // 表单重置
  function reset() {
    form.value = {
      id: null,
      userId: null,
      userName: null,
      deptId: null,
      orgName: null,
      type: null,
      typeName: null,
      typeId: null,
      title: null,
      titleId: null,
      cycle: null,
      scoreOrigin: null,
      addScore: null,
      remark: null,
      createTime: null,
      approvalStatus: null,
      approvalRemark: null,
      approvalRecord: null
    };
    proxy.resetForm("WorkScoreRef");
  }
  
  /** 搜索按钮操作 */
  function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
  }
  
  /** 重置按钮操作 */
  function resetQuery() {
    proxy.resetForm("queryRef");
    handleQuery();
  }
  
  // 多选框选中数据
  function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.id);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
  }
  
  
  function getYearMonthOptions() {
    const now = new Date();
    const curYear = now.getFullYear();
    yearOptions.value = [];
    monthOptions.value = [];
    for (let i = curYear; i > curYear - 5; i--) {
      yearOptions.value.push({ value: i, label: i + "年" });
    }
    monthOptions.value.push({ value: 0, label: "全部" });
    for (let i = 1; i <= 12; i++) {
      monthOptions.value.push({ value: i, label: i + "月" });
    }
  }
  
  /** 查询部门下拉树结构 */
  function getDeptTree() {
    listOrg().then(response => {
      deptOptions.value = proxy.handleTree(response.rows, "deptId");
    });
  };
  
  /** 新增按钮操作 */
  function handleAdd() {
    reset();
    open.value = true;
    title.value = "添加党员积分";
  }
  
  /** 修改按钮操作 */
  function handleUpdate(row) {
    reset();
    const _id = row.id || ids.value
    getWorkScore(_id).then(response => {
      form.value = response.data;
      open.value = true;
      title.value = "修改党员积分";
    });
  }
  
  /** 提交按钮 */
  function submitForm() {
    proxy.$refs["WorkScoreRef"].validate(valid => {
      if (valid) {
        if (form.value.id != null) {
          updateWorkScore(form.value).then(response => {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            getList();
          });
        } else {
          addWorkScore(form.value).then(response => {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            getList();
          });
        }
      }
    });
  }
  
  /** 删除按钮操作 */
  function handleDelete(row) {
    const _ids = row.id || ids.value;
    proxy.$modal.confirm('是否确认删除党员积分编号为"' + _ids + '"的数据项？').then(function() {
      return delWorkScore(_ids);
    }).then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    }).catch(() => {});
  }
  
  /** 导出按钮操作 */
  function handleExport() {
    proxy.download('partybuilding/WorkScore/export', {
      ...queryParams.value
    }, `WorkScore_${new Date().getTime()}.xlsx`)
  }
  
  getYearMonthOptions();
  getDeptTree();
  getList();
  </script>